import { _decorator, dragonBones, Node } from "cc";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { CCComp } from "db://app-game/module/common/CCComp";
import { Role } from "../Role";
import { RoleViewLoader } from "./RoleViewLoader";
import { RoleViewLowerBodyAnimator } from "./RoleViewLowerBodyAnimator";
import { RoleViewUpperBodyAnimator } from "./RoleViewUpperBodyAnimator";
import { AnimatorSwitchManage } from "./animator/AnimatorSwitchManage";

const { ccclass, property } = _decorator;
@ccclass("RoleViewComp")
@ecs.register("RoleView", false)
export class RoleViewComp extends CCComp {
  /** 角色身体 */
  body: Node = null!;
  /** 角色上半身 */
  upperBody: dragonBones.ArmatureDisplay = null!;
  /** 角色下半身 */
  lowerBody: dragonBones.ArmatureDisplay = null!;

  @property({ type: dragonBones.ArmatureDisplay, tooltip: "角色动画" })
  dragonBonesUpperBody: dragonBones.ArmatureDisplay = null!;

  /** 角色动画资源管理 */
  loader: RoleViewLoader = null!;
  /** 角色上半身动画规则管理 */
  upperBodyAnimator: RoleViewUpperBodyAnimator = null!;
  /** 角色下半身动画规则管理 */
  lowerBodyAnimator: RoleViewLowerBodyAnimator = null!;
  /** 动画切换管理 */
  animatorSwitchManage: AnimatorSwitchManage = null!;

  protected onLoad(): void {
    let role = this.ent as Role;

    // 1.获取节点
    this.body = this.node.getChildByName("body");
    this.upperBody = this.body
      .getChildByName("upper-body")
      .getComponent(dragonBones.ArmatureDisplay);
    this.lowerBody = this.body
      .getChildByName("lower-body")
      .getComponent(dragonBones.ArmatureDisplay);

    // 2. 加载角色资源
    this.loader = this.node.addComponent(RoleViewLoader);
    this.node.emit("load", role);

    // 3. 获取动画组件
    this.upperBodyAnimator = this.upperBody.getComponent(
      RoleViewUpperBodyAnimator
    )!;
    this.upperBodyAnimator.role = role;
    this.lowerBodyAnimator = this.lowerBody.getComponent(
      RoleViewLowerBodyAnimator
    )!;
    this.lowerBodyAnimator.role = role;

    // 动画切换管理
    this.animatorSwitchManage = new AnimatorSwitchManage(
      this.upperBodyAnimator,
      this.lowerBodyAnimator
    );
  }

  reset(ent: ecs.Entity): void {
    // 销毁自身节点
    this.node.destroy();
  }
}
